package com.sl.discovery.modular.discovery;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.sl.discovery.api.SquareLakeDiscoveryClient;
import com.sl.discovery.modular.DatabaseManager;
import com.sl.discovery.modular.discovery.domain.entity.AppServiceInstanceDO;
import org.anyline.entity.EntitySet;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import javax.sql.DataSource;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class DbDiscoveryClient implements DiscoveryClient {

    private final DatabaseManager databaseManager;

    public DbDiscoveryClient(DatabaseManager databaseManager) {
        this.databaseManager = databaseManager;

    }


    @Override
    public String description() {
        return "数据库注册中心";
    }

    @Override
    public List<ServiceInstance> getInstances(String serviceId) {

        EntitySet<AppServiceInstanceDO> selects = databaseManager.list();
        List<ServiceInstance> list = selects.stream().map(v -> {
            String metadata = v.getMetadata();
            DefaultServiceInstance serviceInstance = new DefaultServiceInstance(
                    v.getInstanceId(), v.getServiceId(), v.getHost(),
                    v.getPort(),
                    ObjectUtil.equal(v.getSecure(), 1),
                    JSONUtil.toBean(metadata, Map.class)
            );
            if (StrUtil.isNotBlank(v.getUri())) {
                serviceInstance.setUri(URI.create(v.getUri()));
            }
            return (ServiceInstance) serviceInstance;
        }).toList();
        return list;
    }


    @Override
    public List<String> getServices() {
        EntitySet<AppServiceInstanceDO> selects = databaseManager.list();
        return selects.stream().map(AppServiceInstanceDO::getServiceId).distinct().toList();
    }

}
